<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card>
        <el-tabs>
          <!-- 放置页签 -->
          <el-tab-pane label="角色管理">
            <!-- 新增角色按钮 -->
            <el-row style="height:60px">
              <el-button
                icon="el-icon-plus"
                size="small"
                type="primary"
                @click="showDialog=true"
              >新增角色</el-button>
            </el-row>
            <!-- 表格 -->
            <el-table border="" :data="roleList">
              <el-table-column label="序号" width="120" type="index">
                <template #default="{$index}">
                  <!-- 真正的序号应该是
                  之前页面(前一页)的所有数据长度开始 +1 +2 +3 ... -->
                  {{ (page.page-1)*page.pagesize+$index+1 }}
                </template>
              </el-table-column>
              <el-table-column label="角色名称" width="240" prop="name" />
              <el-table-column label="描述" prop="description" />
              <el-table-column label="操作">
                <template #default="{ row }">
                  <el-button size="small" type="success" @click="Allot(row.id)">分配权限</el-button>
                  <el-button size="small" type="primary" @click="editRole(row.id)">编辑</el-button>
                  <el-button size="small" type="danger" @click="delRole(row.id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <!-- 分页组件 -->
            <el-row type="flex" justify="center" align="middle" style="height: 60px">
              <!-- 分页组件 -->
              <el-pagination
                layout="prev,pager,next"
                :total="page.total"
                :page-size="page.pagesize"
                @current-change="currentChange"
              />
            </el-row>
          </el-tab-pane>
          <el-tab-pane label="公司信息">
            <el-alert
              title="对公司名称、公司地址、营业执照、公司地区的更新，将使得公司资料被重新审核，请谨慎修改"
              type="info"
              show-icon
              :closable="false"
            />
            <el-form label-width="120px" style="margin-top:50px">
              <el-form-item label="公司名称">
                <el-input v-model="fromData.name" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="公司地址">
                <el-input v-model="fromData.companyAddress" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="邮箱">
                <el-input v-model="fromData.mailbox" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="备注">
                <el-input v-model="fromData.remarks" type="textarea" :rows="3" disabled style="width:400px" />
              </el-form-item>
            </el-form>
          </el-tab-pane>

        </el-tabs>
      </el-card>
      <el-dialog :title="dialogTitle" :visible="showDialog" @close="btnCancel">
        <el-form ref="roleForm" :model="roleForm" :rules="rules" label-width="120px">
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="roleForm.name" />
          </el-form-item>
          <el-form-item label="角色描述">
            <el-input v-model="roleForm.description" />
          </el-form-item>
        </el-form>
        <!-- 底部 -->
        <el-row slot="footer" type="flex" justify="center">
          <el-col :span="6">
            <el-button size="small" @click="btnCancel">取消</el-button>
            <el-button size="small" type="primary" @click="btnOK">确定</el-button>
          </el-col>
        </el-row>
      </el-dialog>
      <el-dialog title="分配权限" :visible="showPerml" @close="btnClose">
        <el-tree
          ref="Perlist"
          :data="permList"
          :props="{label:'name'}"
          default-expand-all
          :show-checkbox="true"
          check-strictly
          node-key="id"
        />
        <template #footer>
          <el-row type="flex" justify="center">
            <el-button size="small" @click="btnPermOK">确定</el-button>
            <el-button size="small" @click="btnClose">取消</el-button>
          </el-row>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import {
  GetCompany,
  getRoleList,
  delRoleList,
  PutRoleID,
  getRoleID,
  addRole,
  assignPrem
} from '@/api/setting'
import { Getpermission } from '@/api/permission'
import { ListTree } from '@/utils/index.js'
export default {
  data() {
    return {
      showPerml: false,
      permList: [],
      roleID: '',
      fromData: {
        name: '', // 公司名称
        companyAddress: '', // 公司地址
        remarks: '', // 邮箱
        mailbox: ''// 备注
      },
      page: {
        page: 1,
        pagesize: 2,
        total: 0
      },
      roleList: [],
      showDialog: false,
      roleForm: {
        name: '',
        description: ''
      },
      rules: {
        name: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }]
      }
    }
  },
  computed: {
    dialogTitle() {
      return this.roleForm.id ? '新增角色' : '编辑角色'
    }
  },
  created() {
    this.GetCompany()
    this.getRoleList()
    this.Getpermission()
  },
  methods: {
    async GetCompany() {
      this.fromData = await GetCompany(this.$store.state.user.userInfo.companyId)
      // console.log(res)
    },
    async getRoleList() {
      const { rows, total } = await getRoleList(this.page)
      this.roleList = rows
      this.page.total = total
      // console.log(this.roleList)
    },
    currentChange(newPage) {
      // console.log(newPage)
      // 修改页码配置
      this.page.page = newPage
      // 发请求
      this.getRoleList()
    },
    async delRole(id) {
      console.log(id)
      try {
        // 二次询问
        await this.$confirm('是否确定删除')
        // 发送删除请求
        await delRoleList(id)
        // 加载数据
        this.getRoleList()
        // 提示用户删除成功
        this.$message.success('删除成功')
      } catch (error) {
        console.log(error)
      }
    },
    btnCancel() {
      this.roleForm = {
        name: '',
        description: ''
      }
      this.$refs.roleForm.resetFields()
      this.showDialog = false
    },
    async btnOK() {
      console.log(this.roleForm)
      try {
        await this.$refs.roleForm.validate()
        if (this.roleForm.id) {
          await PutRoleID(this.roleForm)
        } else {
          await addRole(this.roleForm)
        }

        this.$message.success('操作成功')
        this.showDialog = false
        this.getRoleList()
      } catch (error) {
        console.log(error)
      }
    },
    async editRole(id) {
      this.roleForm = await getRoleID(id)
      this.showDialog = true
    },
    async Getpermission() {
      const res = await Getpermission()
      // console.log(res)
      this.permList = ListTree(res.filter(e => e.enVisible === '1'), '0')
    },
    async Allot(id) {
      this.roleID = id
      this.showPerml = true
      const { permIds } = await getRoleID(id)
      // console.log(res)
      this.$nextTick(() => {
        /*
           setCheckedKeys 设置目前勾选的节点，使用此方法必须设置 node-key 属性
           (keys, leafOnly) 接收两个参数，
           1. 勾选节点的 key 的数组
           2. boolean 类型的参数，若为 true 则仅设置叶子节点的选中状态，默认值为 false
         */
        this.$refs.Perlist.setCheckedKeys(permIds)
      })
    },
    async btnPermOK() {
      const data = {
        id: this.roleID,
        /*
           getCheckedKeys
           若节点可被选择（即 show-checkbox 为 true），则返回目前被选中的节点的 key 所组成的数组
           (leafOnly) 接收一个 boolean 类型的参数，若为 true 则仅返回被选中的叶子节点的 keys，默认值为 false
         */
        permIds: this.$refs.Perlist.getCheckedKeys()
      }
      await assignPrem(data)
      this.$message.success('修改成功')
      this.showPerml = false
    },
    btnClose() {
      /*
          setCheckedKeys
         	设置目前勾选的节点，使用此方法必须设置 node-key 属性
          (nodes) 接收勾选节点数据的数组
       */
      this.$refs.Perlist.setCheckedKeys([])
      this.showPerml = false
    }

  }
}
</script>

<style>

</style>
